package com.sjf.JavaNIO.channel;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * FileChannel通过buffer缓冲区对文件进行写操作
 * 缓冲区的数据写入到文件中可以通过Stream流的方式，此处用到Channel管道的方式来
 *
 * @author <huangtang>
 * @since 2022/4/13 14:45
 **/
public class FileChannelDemo2 {

    public static void main ( String[] args ) throws Exception {
        //打开FileChannel
        RandomAccessFile aFile = new RandomAccessFile ("D:\\atguigu\\test\\01.txt" , "rws");
        FileChannel channel = aFile.getChannel ();
        //创建字节缓冲区
        ByteBuffer buffer = ByteBuffer.allocate (1024);

        String newData = "test write data 1111 " + System.currentTimeMillis ();
        buffer.clear ();

        //写入内容到buffer中
        buffer.put (newData.getBytes (StandardCharsets.UTF_8));

        buffer.flip ();//从写入模式转换到读出模式
        //FileChannel从buffer里读数据并写入文件中

        while (buffer.hasRemaining ()) {
            channel.write (buffer);
        }

        //channel.truncate (3);
        //关闭
        channel.close ();
    }
}
